<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>

<style>
    #left{
        float: left;
        width: 30%;
        height: 500px;
        margin-left: 200px;
    }
    #right{
        float: right;
        width: 30%;
        height: 1000px;
    }
    #top{
        margin-top: 50px;
        float: top;
        width: 30%;
        height: 250px;
    }
    #content{
        border: royalblue 1px solid;
        width: 500px;
        height: 300px;
    }
    #input{
        margin-top: 20px;
        width: 500px;
        height: 200px;
    }
    #input input{
        width: 100%;
        height: 100px;
    }
    #input button{
        float: right;
    }
    #mes_left{
        float: left;

    }
    #mes_right{
        float: right;
        width: 50%;
        text-align: right;
    }
    span{
        font-size:10px;
    }
</style>
<body>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>

<h3 style="text-align: center" id="username"></h3>
<div>
    <div id="left">
        <h4 id="new"></h4>

        <div id="content">

        </div>
        <div id="input">
            <input type="text" id="input_text">
            <button id="submit">发送</button>
        </div>
    </div>
    <div id="right">
        <div id="top">
            <p>在线的好友</p>
            <div id="hylist">

            </div>
        </div>
    </div>
</div>


<script>
    var username;
    var toName;
    $(function () {

        $.ajax({
            url:"../patient/getPatientBySession",
            success:function (res) {
                username = res.data.patientName;
                $("#username").html("用户："+ username +"<span>在线</span>");
                // $("#username").html("用户：123<span>在线</span>");
            },
            async:false //同步请求，只有上面好了才会接着下面
        });

        var ws = new WebSocket("ws://localhost:8080/chat");
        ws.onopen = function (ev) {
            $("#username").html("用户："+ username +"<span>在线</span>");
        }
        //接受消息
        ws.onmessage = function (ev) {
            var datastr = ev.data;
            var res = JSON.parse(datastr);

            console.log(res)
            //判断是否是系统消息
            if(res.system){
                //好友列表
                //系统广播
                var names = res.message;
                var userlistStr = "";
                for (var name of names){
                    if (name != username){
                        userlistStr += "<button type='button' class='nameBtn'>"+name+"</button><br>";
                    }
                };
                $("#hylist").html(userlistStr);

            }else {
                //不是系统消息

                // document.write(strDate);
                var str = "<span id='mes_left'>"+res.message+"</span></br>";
                if (toName == res.fromName)
                    $("#content").append(str);
                // console.log(res.fromName,str)
                var chatdata = sessionStorage.getItem(res.fromName);
                if (chatdata != null){
                    str = chatdata + str;
                }
                sessionStorage.setItem(res.fromName,str);

            };
        },
        ws.onclose = function (ev) {
            $("#username").html("用户："+ username +"<span>离线</span>");
        }

        function repair(i){
            if (i >= 0 && i <= 9) {
                return "0" + i;
            } else {
                return i;
            }
        }
        //发送消息
        $("#submit").click(function () {
            let date = new Date();//当前时间
            let year = date.getFullYear() //年
            let month = repair(date.getMonth() + 1);//月
            let day = repair(date.getDate());//日
            let hour = repair(date.getHours());//时
            let minute = repair(date.getMinutes());//分
            let second = repair(date.getSeconds());//秒

            //当前时间
            let curTime = year + "-" + month + "-" + day
                + " " + hour + ":" + minute + ":" + second;

            //获取输入的内容
            var data = $("#input_text").val();
            $("#input_text").val("");
            var json = {"toName": toName ,"message": data};
            //将数据展示在聊天区
            var str = "<span id='mes_right'>"+ data +"("+curTime+")"+"</span></br>";
            $("#content").append(str);

            var chatdata = sessionStorage.getItem(toName);
            if (chatdata != null){
                str = chatdata + str;
            }
            sessionStorage.setItem(toName,str);
            // console.log(json);
            //发送数据
            ws.send(JSON.stringify(json));
        })
    });

    $(document).on("click",".nameBtn",function () {

        toName = $(this).text();
        //清空聊天区
        $("#content").html("");
        $("#new").html("当前正与"+toName+"聊天");
        var chatdata = sessionStorage.getItem(toName);
        if (chatdata != null){
            $("#content").html(chatdata);
        }
    });
</script>
</body>
</html>